using ERPBackend.Data;
using ERPBackend.Models;
using ERPBackend.Services;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ERPBackend.Services
{
    public class CustomerService : ICustomerService
    {
        private readonly ApplicationDbContext _context;

        public CustomerService(ApplicationDbContext context)
        {
            _context = context;
        }

        public async Task<IEnumerable<Customer>> GetAllCustomersAsync()
        {
            return await _context.Customers.ToListAsync();
        }

        public async Task<Customer> GetCustomerByIdAsync(int id)
        {
            return await _context.Customers
                .Include(c => c.CustomerContacts)
                .FirstOrDefaultAsync(c => c.Id == id);
        }

        public async Task<Customer> CreateCustomerAsync(Customer customer)
        {
            // 确保客户编码唯一
            if (await _context.Customers.AnyAsync(c => c.CustomerCode == customer.CustomerCode))
            {
                throw new Exception("客户编码已存在");
            }

            // 设置默认值
            if (string.IsNullOrEmpty(customer.Status))
            {
                customer.Status = "启用";
            }

            _context.Customers.Add(customer);
            await _context.SaveChangesAsync();

            return customer;
        }

        public async Task<bool> UpdateCustomerAsync(Customer customer)
        {
            var existingCustomer = await _context.Customers.FindAsync(customer.Id);
            if (existingCustomer == null)
            {
                return false;
            }

            // 检查客户编码是否已被其他客户使用
            if (existingCustomer.CustomerCode != customer.CustomerCode &&
                await _context.Customers.AnyAsync(c => c.CustomerCode == customer.CustomerCode))
            {
                throw new Exception("客户编码已存在");
            }

            // 更新客户信息
            _context.Entry(existingCustomer).CurrentValues.SetValues(customer);

            // 处理客户联系人
            // 删除已移除的联系人
            var existingContacts = await _context.CustomerContacts
                .Where(cc => cc.CustomerId == customer.Id)
                .ToListAsync();

            foreach (var existingContact in existingContacts)
            {
                if (!customer.CustomerContacts.Any(cc => cc.Id == existingContact.Id))
                {
                    _context.CustomerContacts.Remove(existingContact);
                }
            }

            // 添加或更新联系人
            foreach (var contact in customer.CustomerContacts)
            {
                if (contact.Id == 0)
                {
                    // 新联系人
                    contact.CustomerId = customer.Id;
                    _context.CustomerContacts.Add(contact);
                }
                else
                {
                    // 更新现有联系人
                    var existingContact = existingContacts.FirstOrDefault(cc => cc.Id == contact.Id);
                    if (existingContact != null)
                    {
                        _context.Entry(existingContact).CurrentValues.SetValues(contact);
                    }
                }
            }

            await _context.SaveChangesAsync();
            return true;
        }

        public async Task<bool> DeleteCustomerAsync(int id)
        {
            var customer = await _context.Customers.FindAsync(id);
            if (customer == null)
            {
                return false;
            }

            // 检查是否有相关业务数据
            // 这里可以添加检查逻辑，如是否有销售订单、合同等

            // 删除客户联系人
            var contacts = await _context.CustomerContacts
                .Where(cc => cc.CustomerId == id)
                .ToListAsync();
            _context.CustomerContacts.RemoveRange(contacts);

            // 删除客户
            _context.Customers.Remove(customer);
            await _context.SaveChangesAsync();
            return true;
        }

        public async Task<bool> DisableCustomerAsync(int id)
        {
            var customer = await _context.Customers.FindAsync(id);
            if (customer == null)
            {
                return false;
            }

            customer.Status = "禁用";
            await _context.SaveChangesAsync();
            return true;
        }

        public async Task<bool> EnableCustomerAsync(int id)
        {
            var customer = await _context.Customers.FindAsync(id);
            if (customer == null)
            {
                return false;
            }

            customer.Status = "启用";
            await _context.SaveChangesAsync();
            return true;
        }

        public async Task<IEnumerable<Customer>> SearchCustomersAsync(string keyword, string customerType, string status)
        {
            var query = _context.Customers.AsQueryable();

            if (!string.IsNullOrEmpty(keyword))
            {
                query = query.Where(c =>
                    c.CustomerCode.Contains(keyword) ||
                    c.CustomerName.Contains(keyword) ||
                    c.ShortName.Contains(keyword));
            }

            if (!string.IsNullOrEmpty(customerType))
            {
                query = query.Where(c => c.CustomerType == customerType);
            }

            if (!string.IsNullOrEmpty(status))
            {
                query = query.Where(c => c.Status == status);
            }

            return await query.ToListAsync();
        }
    }
}